//
//  SetPasswordTableVC.m
//  Cunli
//
//  Created by lilubin on 15/7/22.
//  Copyright (c) 2015年 lilubin. All rights reserved.
//

#import "SetPasswordTableVC.h"
#import "SettingTableViewCell.h"
#import "NSString+MD5.h"
#import "MyDataService.h"
#import "Config.h"
#import "CompleteDataTableVC.h"

#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height

static NSString *kSettingCellID = @"SettingTableViewCell";

@interface SetPasswordTableVC () <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UITableView *tableView;

@end

@implementation SetPasswordTableVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavAttributes];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)setNavAttributes
{
    UIImageView *navBgImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 64)];
    [navBgImgView setImage:[UIImage imageNamed:@"NavigationBgImage"]];
    [self.view addSubview:navBgImgView];
    
    UILabel *navLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, kScreenWidth, 44)];
    [navLabel setText:@"设置密码"];
    [navLabel setTextColor:[UIColor whiteColor]];
    [navLabel setFont:[UIFont boldSystemFontOfSize:19]];
    navLabel.textAlignment = NSTextAlignmentCenter;
    [navBgImgView addSubview:navLabel];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(8, 27, 30, 30);
    backBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
    [backBtn setImage:[UIImage imageNamed:@"regback01"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backBtn];
    
    UIButton *nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    nextBtn.frame = CGRectMake(kScreenWidth-72, 27, 65, 30);
    nextBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
    [nextBtn addTarget:self action:@selector(nextAction) forControlEvents:UIControlEventTouchUpInside];
    [nextBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.view addSubview:nextBtn];
                     
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight-64) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.bounces = NO;
    [self.view addSubview:_tableView];
    
    [_tableView setBackgroundColor:[UIColor colorWithHexString:UIBgColorValue]];
    [self.view setBackgroundColor:[UIColor colorWithHexString:UIBgColorValue]];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SettingTableViewCell *cell = [[NSBundle mainBundle] loadNibNamed:kSettingCellID owner:self options:nil].lastObject;
    if (indexPath.row == 0) {
        cell.titleLabel.text = @"密码：";
        cell.textField.placeholder = @"密码";
        cell.textField.font = [UIFont systemFontOfSize:17];
        cell.textField.secureTextEntry = YES;
    }
    else
    {
        cell.titleLabel.text = @"确认密码：";
        cell.textField.placeholder = @"确认密码";
        cell.textField.font = [UIFont systemFontOfSize:17];
        cell.textField.secureTextEntry = YES;
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 61)];
    UILabel *promptLabel = [[UILabel alloc] initWithFrame:CGRectMake(8, 5, kScreenWidth, 21)];
    promptLabel.text = @"密码由英文字母及数字组成，不少于6位";
    promptLabel.font = [UIFont systemFontOfSize:12];
    promptLabel.textColor = [UIColor darkGrayColor];
    
    [footerView addSubview:promptLabel];
    return footerView;
}


- (void)backAction
{
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (void)nextAction
{
    SettingTableViewCell *cell1 = (SettingTableViewCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    SettingTableViewCell *cell2 = (SettingTableViewCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    NSString *pwdStr = cell1.textField.text;
    NSString *rePwdStr = cell2.textField.text;

    if (pwdStr.length < 6 || rePwdStr.length < 6) {
        [self showHUDWithText:@"密码需要大于6位" andImage:@"error"];
        return;
    }
    if (![cell1.textField.text isEqualToString:cell2.textField.text]) {
        [self showHUDWithText:@"密码不一致" andImage:@"error"];
        return;
    }
    
    //设置请求参数
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:5];
    [params setObject:[Config getOwnUsername] forKey:@"username"];
    [params setObject:pwdStr forKey:@"password"];
    [params setObject:rePwdStr forKey:@"repassword"];
    [params setObject:_code_token forKey:@"code_token"];
    [params setObject:[NSString getSignFromParam:params] forKey:@"sign"];
    
    [MyDataService requestURL:@"regpasswd.php" httpMethod:@"POST" params:params fileDatas:nil complection:^(id result) {
        NSLog(@"result:%@", result);
        NSString *response = [result objectForKey:@"response"];
        NSDictionary *userInfoDic = [result objectForKey:@"userinfo"];
        NSString *access_token = [userInfoDic objectForKey:@"access_token"];
        NSDictionary *invitDic = [userInfoDic objectForKey:@"invit"];
        NSString *is_invited = invitDic[@"is_invint"];
        
        [Config saveUserID:userInfoDic[@"userid"]];
        
        if ([response isEqualToString:@"regpasswd"]) {
            [Config showHUDWithText:@"注册成功" andImage:@"done"];
            [self pushToNextVCWithAccessToken:access_token isInvited:is_invited];
            [Config saveUserPwd:rePwdStr];
        }
        else
        {
            NSDictionary *errorDic = [result objectForKey:@"error"];
            NSString *errorStr = [errorDic objectForKey:@"text"];
            [self showHUDWithText:errorStr andImage:@"error"];
            return;
        }
        
    } failureAction:^{
        [self showHUDWithText:@"设置密码失败" andImage:@"error"];
    }];
}

- (void)pushToNextVCWithAccessToken:(NSString *)accessToken isInvited:(NSString *)is_invited
{
    CompleteDataTableVC *completeDataVC = [[CompleteDataTableVC alloc] init];
    completeDataVC.access_token = accessToken;
    completeDataVC.is_invint = is_invited;
    completeDataVC.modalTransitionStyle = UIModalTransitionStyleCoverVertical ;
    completeDataVC.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:completeDataVC animated:YES completion:NULL];
}

- (void)showHUDWithText:(NSString *)str andImage:(NSString *)imgStr
{
    MBProgressHUD *hud = [Config createHUD];
    hud.mode = MBProgressHUDModeCustomView;
    hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imgStr]];
    hud.labelText = str;
    [hud hide:YES afterDelay:1];
}




@end
